package com.hm.utils;

import com.alibaba.druid.pool.DruidDataSource;
import org.apache.ibatis.datasource.pooled.PooledDataSourceFactory;
import org.apache.ibatis.datasource.unpooled.UnpooledDataSourceFactory;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import javax.sql.DataSource;
import java.io.IOException;
import java.io.InputStream;
import java.sql.SQLException;

/**
 * This class is for com.hm.utils
 *
 * @author 李聪
 * @version 2023/10/21
 */
public class MybatisUtil {
    private static SqlSessionFactory factory = null;
    private static ThreadLocal<SqlSession> tl = new ThreadLocal<SqlSession>();
    static {
        // 1 读取配置文件 config.xml
        InputStream in = null;
        try {
            in = Resources.getResourceAsStream("mybatis-config.xml");
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            throw new RuntimeException(e);
        }
        // 2 创建SqlSessionFactory
        factory = new SqlSessionFactoryBuilder().build(in);
    }

    public static SqlSession openSession() {
        // 3 创建SqlSession
        SqlSession sqlSession = tl.get();
        if (sqlSession == null) {
            sqlSession = factory.openSession();
            tl.set(sqlSession);
        }
        return sqlSession;

    }

    public static void close(SqlSession sqlSession) {

        if (sqlSession != null) {
            tl.remove();
            sqlSession.close();
        }

    }
}
